from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import logout as out

# Create your views here.
from django.urls import reverse
from django.views import View

from user.forms import UserLRForm


class UserView(View):
    def get(self, request):
        form = UserLRForm()
        return render(request, 'user/register.html', {'form': form})

    def post(self, request):
        # print(request.POST)
        # 获取数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(username, password)

        # 校验数据
        if not username:
            message = '注册失败，请输入用户名'
        elif 2 > len(username) or len(username) > 10:
            message = '注册失败。用户名长度为2-10'
        elif not password:
            message = '注册失败，请输入密码'
        elif 2 > len(password) or len(password) > 10:
            message = '注册失败。密码长度为2-20'
        else:
            # 持久化操作数据
            user = User(username=username)
            user.set_password(password)
            try:
                user.save()
            except IntegrityError:
                message = '用户名已被使用'
            else:
                message = '注册成功'
                return redirect(reverse('login'))
        return render(request, 'user/register.html', {'message': message})


class LoginView(View):
    def get(self, request):
        form = UserLRForm()  # 创建了表单对象
        return render(request, 'user/login.html', {'form': form})

    def post(self, request):
        form = UserLRForm(request.POST)  # 创建了表单对象，并绑定用户输入的数据

        # 校验数据
        if form.is_valid():
            # 获取通过校验后的数据
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            # # 查询数据库，对比账号和密码是否正确
            # try:
            #     user = User.objects.get(username=username)  # 查询数据库中是否有这个账号
            # except User.DoesNotExist:
            #     message = '账号不存在'
            # else:
            #     # 有账号，校验密码是否正确
            #     if user.check_password(password):
            #         # 账号密码正确，创建session信息，会话维持
            #         request.session['username'] = username
            #         # request.session.set_expiry(300)  # 设置会话过期时间
            #         return redirect(reverse('index'))
            #     else:
            #         message = '密码错误'
            # 校验身份 session auth系统来完成认证，然后使用内置login
            user = authenticate(username=username, password=password)
            if user:
                print(user)
                # 校验通过,把登录后的用户信息放到请求对象中
                login(request, user)
                next_url = request.GET.get('username')
                print(next_url)
                if next_url:
                    return redirect(next_url)
                return redirect(reverse('index'))

        # return render(request, 'user/login.html', {'message': message, 'form': form})
        return render(request, 'user/login.html', {'form': form})


def logout(request, **kwargs):
    out(request)  # 调用auth系统中的logout方法传入请求对象完成退出，把请求对象用的登录用户信息给清除掉
    return redirect(reverse('login'))
